#include "mf_bstim.h"
#include "mf_iwdt.h"
#include "log.h"
#include "MLCD.h"

const static char *TAG = "mf_bstim.c";

volatile mf_bstim_t mf_bstim_panel;

/**
 * @brief mf_bstim_init
 * @param prescaler [ 16bit ]
 * @param autoReload [ 32bit ]
 * @return FL_ErrorStatus (1 or 0)
 * @note Tout = (Tprescaler)*(autoReload) / clockSource[Hz] [second]
 */
FL_ErrorStatus mf_bstim_init(uint32_t prescaler, uint32_t autoReload)
{
    FL_ErrorStatus ret = FL_PASS;
    FL_BSTIM32_InitTypeDef bstim32;
    FL_NVIC_ConfigTypeDef nvic;

    /* set bstim conf start */
    bstim32.prescaler = prescaler - 1;   /* Tout = (Tprescaler+1)*(autoReload+1) / clockSource [second] */
    bstim32.autoReload = autoReload - 1; /* Tout = (Tprescaler+1)*(autoReload+1) / clockSource [second] */
    bstim32.autoReloadState = FL_ENABLE;
    bstim32.clockSource = FL_RCC_BSTIM32_CLK_SOURCE_APB2CLK;
    ret |= FL_BSTIM32_Init(MF_BSTIM_BASE, &bstim32);
    /* set bstim conf end */

    /* conf bstim IT start */
    FL_BSTIM32_ClearFlag_Update(MF_BSTIM_BASE);
    FL_BSTIM32_EnableIT_Update(MF_BSTIM_BASE);
    nvic.preemptPriority = 0x01;
    FL_NVIC_Init(&nvic, BSTIM_IRQn);
    /* conf bstim IT end */

    mf_bstim_enable(FL_DISABLE); /* enable bstim */

    return ret;
}

/**
 * @brief mf_bstim_enable
 * @param FL_FunState (1 or 0)
 * @return None
 */
void mf_bstim_enable(FL_FunState state)
{
    switch (state)
    {
    case FL_DISABLE:
        FL_BSTIM32_Disable(MF_BSTIM_BASE); /* BSTIM_CR1.CEN->0 */
        break;
    case FL_ENABLE:
        FL_BSTIM32_Enable(MF_BSTIM_BASE); /* BSTIM_CR1.CEN->1 */
        break;
    default:
    	MY_LOGI(TAG, "func[mf_bstim_enable] parameter err.\r\n");
        break;
    }
}

volatile mf_bstim_t *bstim_get_data(void)
{
    return &mf_bstim_panel;
}

/**
 * @brief BSTIM_IRQHandler
 * @return None
 * @note BSTIM中断函数
 */
void BSTIM_IRQHandler(void)
{
    if (FL_BSTIM32_IsActiveFlag_Update(MF_BSTIM_BASE))
    {
        FL_BSTIM32_ClearFlag_Update(MF_BSTIM_BASE);
        /* run your proc start */
        mf_bstim_panel.time_count += 1;      /* add time_count */
        mf_bstim_panel.iwdt_time_count += 1; /* add iwdt_time_count */
        mlcd_refresh();                      /* refresh mlcd -> period 30ms */
        mf_iwdt_refresh();                   /* refresh iwdt */
        /* run your proc end */
    }
}
